package Careful;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

public class MapSort {
    public static void main(String[] args) {

        Map<Integer,String> map = creatTreeMapOrderByKey();
        List<Entry<Integer, String>> entries = sortByMapValue(map);
        for(Map.Entry<Integer,String> out : entries){
            System.out.println(out.getKey()+":"+out.getValue());
        }

    }

    public static Map<Integer,String> creatTreeMapOrderByKey(){
        TreeMap<Integer,String> map = new TreeMap<>();
        map.put(2,"Tom");
        map.put(5,"Sam");
        map.put(1,"July");
        map.put(10,"Jack");
        return map;
    }
    public static Map<Integer,String> creatTreeMapOrderByKey2(){
        TreeMap<Integer,String> map = new TreeMap<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2-o1;
            }
        });
        map.put(2,"Tom");
        map.put(5,"Sam");
        map.put(1,"July");
        return map;
    }

    public static List<Entry<Integer,String>> sortByMapValue(Map<Integer,String> map){
        List<Entry<Integer,String>> list = new ArrayList<Entry<Integer, String>>(map.entrySet());
        Collections.sort(list, new Comparator<Entry<Integer, String>>() {
            @Override
            public int compare(Entry<Integer, String> o1, Entry<Integer, String> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        });
        return list;
    }

    public static void printMap(Map<Integer,String> map){
        for(Integer key:map.keySet()){
            System.out.println(key+":"+map.get(key));
        }
    }
    public static void printMap2(Map<Integer,String> map){
        Set<Entry<Integer,String>> set = map.entrySet();
        for(Map.Entry out:set){
            System.out.println(out.getKey()+":"+out.getValue());
        }
    }



}
